package com.study.signin_demo2.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.study.signin_demo2.entity.Order;
import com.study.signin_demo2.entity.Products;
import com.study.signin_demo2.service.IOrderService;
import com.study.signin_demo2.service.IProductsService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * @author whx
 * @date 2022/2/22
 */
@RestController
@RequestMapping("order")
@AllArgsConstructor
public class OrderController {

    private IOrderService orderService;

    private IProductsService productsService;


    @PostMapping("save")
    public Boolean save(@RequestBody Order order){
        // TODO order表为关键字
        if(null != order.getId()){
            // 修改操作
            HashMap<String,Object> map = new HashMap<>();
            map.put("order_id",order.getId());
            productsService.removeByMap(map);
        }
        Boolean res = orderService.saveOrUpdate(order);
        if(null != order.getProductsList() && order.getProductsList().size() > 0){
//            productsService.saveBatch(order.getProductsList());
            for (Products products : order.getProductsList()) {
                products.setOrderId(order.getId());
                productsService.save(products);
            }
        }
        return res;
    }

    /**
     * 查询
     * @param id
     * @return
     */
    @GetMapping("getById")
    public Order getById(Long id){
        Order one = orderService.getById(id);
        List<Products> list = productsService.list(Wrappers.<Products>lambdaQuery().eq(Products::getOrderId, id));
        one.setProductsList(list);
        return one;
    }






}
